/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import database.DBConnection;
import java.util.ArrayList;
import java.util.HashMap;
import model.Room;

/**
 *
 * @author Martin Mohr Pedersen
 */
public class RoomDAO {
    
    public Room getRoom(Integer id) {
        String sql = "SELECT * FROM room WHERE id = ?";
        Object[] args = new Object[] {id};
        
        return findOne(sql, args);
    }

    private Room findOne(String sql, Object[] args) {
        ArrayList<HashMap<String, Object>> results = DBConnection.getInstance().executeSelect(sql, args);
        
        return unpackOne(results);
    }
    
    private Room unpackOne(ArrayList<HashMap<String, Object>> results) {
        Room[] rooms = unpack(results);
        if (rooms.length > 0){
            return rooms[0];
        }
        return null;
    }

    private Room[] unpack(ArrayList<HashMap<String, Object>> results) {
        ArrayList<Room> rooms = new ArrayList<Room>();
        Room room;
        
        for (HashMap<String, Object> row : results) {
            room = new Room();
            
            room.setName(row.get("name").toString());
            room.setId(Integer.parseInt(row.get("id").toString()));
            
            rooms.add(room);
        }
        return rooms.toArray(new Room[rooms.size()]);
    }   
}
